package com.rz.quartz.controller;

import com.rz.quartz.entity.JobAndTrigger;
import com.rz.quartz.job.MyJob;
import com.rz.quartz.job.MyJob2;
import org.quartz.*;
import org.quartz.impl.StdScheduler;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

/**
 * @program: quartz
 * @description: 控制quartz定时任务的api
 * @author: rZ
 * @create: 2020-02-10 10:59
 **/
@RestController
public class QuartzControllerApi {

    //注入QuartzConfig 自己配置的scheduler
    @Resource(name = "scheduler")
    private StdScheduler scheduler;

    /**
     * 删除定时任务job
     * @return
     * @throws SchedulerException
     */
    @RequestMapping("/delete_job")
    public String deleteJob(JobAndTrigger jt) throws SchedulerException {
        JobKey jobKey = new JobKey(jt.getJobName(),jt.getJobGroup());
        JobDetail jobDetail = scheduler.getJobDetail(jobKey);
        if (jobDetail == null) {
            return "jobDetail is null";
        }else if (scheduler.checkExists(jobKey)){
            return "jobKey is not exists";
        }else {
            scheduler.deleteJob(jobKey);
            return "定时任务删除成功";
        }
    }

    /**
     * 暂停定时任务job
     * @return
     * @throws SchedulerException
     */
    @RequestMapping("/pause_job")
    public String pauseJob(JobAndTrigger jt) throws SchedulerException {
       JobKey jobKey = new JobKey(jt.getJobName(),jt.getJobGroup());
        JobDetail jobDetail = scheduler.getJobDetail(jobKey);
        if (jobDetail == null) {
            return "jobName或jobGroup错误，定时任务暂停失败";
        }else {
            scheduler.pauseJob(jobKey);
        }
        return "定时任务暂停成功";
    }

    /**
     * 动态添加定时任务
     * @param jt
     * @return
     * @throws SchedulerException
     */
    @RequestMapping("/add_job")
    public String addJob(JobAndTrigger jt) throws SchedulerException {
        JobDetail jobDetail = null;
        //判断group组别，新建任务
        if ("jobOne".equals(jt.getJobGroup())){
            jobDetail = JobBuilder.newJob(MyJob.class).withIdentity(jt.getJobName(),jt.getJobGroup()).build();
        }
        if ("jobTwo".equals(jt.getJobGroup())){
            jobDetail = JobBuilder.newJob(MyJob2.class).withIdentity(jt.getJobName(),jt.getJobGroup()).build();
        }
        //验证cron表达式
        if (!CronExpression.isValidExpression(jt.getCronExpression())){
            System.out.println("cron表达式无效！");
        }
        //定义一个Trigger，触发条件类
        TriggerBuilder<Trigger> triggerBuilder = TriggerBuilder.newTrigger();
        //创建触发器：trigger
        Trigger trigger = triggerBuilder.withIdentity(jt.getJobName(), jt.getJobGroup())//定义name和group
                .withSchedule(CronScheduleBuilder.cronSchedule(jt.getCronExpression()))//定义cron表达式
                .build();
        scheduler.scheduleJob(jobDetail,trigger);
        return "定时任务创建成功";
    }

    /**
     * 获取job的状态
     * @param jt
     * @return
     * @throws SchedulerException
     */
    @RequestMapping("/get_job_state")
    public String getJobState(JobAndTrigger jt) throws SchedulerException {
        TriggerKey triggerKey = new TriggerKey(jt.getJobName(),jt.getJobGroup());
        return scheduler.getTriggerState(triggerKey).name();
    }

    /**
     * 暂停所有任务
     * @throws SchedulerException
     */
    @RequestMapping("pause_all_job")
    public void pauseAllJob() throws SchedulerException {
        scheduler.pauseAll();
    }

    /**
     * 恢复所有任务
     * @throws SchedulerException
     */
    @RequestMapping("resume_all_job")
    public void resumeAllJob() throws SchedulerException {
        scheduler.resumeAll();
    }

    /**
     * 暂停某个定时任务
     * @param jt
     * @return
     * @throws SchedulerException
     */
    @RequestMapping("resume_job")
    public String resumeJob(JobAndTrigger jt) throws SchedulerException {
        JobKey jobKey = new JobKey(jt.getJobName(),jt.getJobGroup());
        JobDetail jobDetail = scheduler.getJobDetail(jobKey);
        if (jobDetail == null) {
            return "jobName或jobGroup错误，定时任务暂停失败";
        }else {
            scheduler.pauseJob(jobKey);
            return "任务暂停成功！";
        }
    }

    /**
     * 修改定时任务
     * @param jt
     * @return
     * @throws SchedulerException
     */
    @RequestMapping("/modify_job")
    public String modifyJob(JobAndTrigger jt) throws SchedulerException {
        //验证cron表达式
        if (!CronExpression.isValidExpression(jt.getCronExpression())){
            return "cron表达式错误!";
        }
        TriggerKey triggerKey = new TriggerKey(jt.getJobName(),jt.getJobGroup());
        JobKey jobKey = new JobKey(jt.getJobName(),jt.getJobGroup());
        //判断是否存在job和trigger
        if (scheduler.checkExists(triggerKey) && scheduler.checkExists(jobKey)){
            CronTrigger cronTrigger = (CronTrigger) scheduler.getTrigger(triggerKey);
            ////表达式调度构建器,不立即执行
            CronScheduleBuilder cronScheduleBuilder = CronScheduleBuilder.cronSchedule(jt.getCronExpression()).withMisfireHandlingInstructionDoNothing();
            //按新的cronExpression表达式重新构建trigger
            cronTrigger = cronTrigger.getTriggerBuilder().withIdentity(triggerKey).withSchedule(cronScheduleBuilder).build();
            scheduler.rescheduleJob(triggerKey,cronTrigger);
            return "成功修改";
        }else {
            return "修改失败";
        }
    }
}
